//
//  MyDuoBaoView.m
//  夺宝吧
//
//  Created by xiaocai on 15/7/13.
//  Copyright (c) 2015年 FangYuan. All rights reserved.
//

#import "MyDuoBaoView.h"
#import "PayForDbbVC.h"
#import "MoreVC.h"
#import "DuoBaoHisVC.h"
#import "SettingVC.h"
#import "RewardsVC.h"
#import "MingXiVC.h"
#import "AddressVC.h"
#import "ShowOrderVC.h"
#import "JSBadgeView.h"
#import "NewsModel.h"
#import "NewsVC.h"
#import "UMSocial.h"
#import "UMengRgt.h"
#import "WYPublicWeb.h"
#import "ChongZhiController.h"

//获取意见反馈接口
#define FEEDBACK_URL @"api/ApiUser/feedback"
//获取充值页面的配置信息
#define PEIZHI_URL @"/api/ApiPay/getRechargeConfig"
//获取系统消息
#define NEWS_URL @"/api/ApiMisc/getSysMsgs"
@interface MyDuoBaoView ()<UMSocialUIDelegate , UIAlertViewDelegate>
{
    __weak IBOutlet UIImageView *headerImg;
    
    __weak IBOutlet UIView *bgnavi;
    __weak IBOutlet UILabel *countLab;
    
    __weak IBOutlet UILabel *moneyLab;
    
    __weak IBOutlet UILabel *JiFenLab;
    
    __weak IBOutlet UIButton *ChongZhiBtn;
    
    
    __weak IBOutlet UIImageView *midIng;
    
    __weak IBOutlet UIImageView *newImg;
    
    __weak IBOutlet UILabel *lab1;
    __weak IBOutlet UILabel *lab2;
    __weak IBOutlet UILabel *lab3;
    __weak IBOutlet UILabel *lab4;
    __weak IBOutlet UILabel *lab5;
    
    //圆角通知
    JSBadgeView *badgeView;
    //装新闻消息的数组
    NSMutableArray *_data;
    
    __weak IBOutlet UIButton *loginBtn;
    
    
    
    
    __weak IBOutlet UIImageView *customService3;

    __weak IBOutlet UILabel *customService2;
    
    
    __weak IBOutlet UIImageView *customService1;
    
  
    
    __weak IBOutlet UIButton *customServiceBtn;
    
}
@end
@implementation MyDuoBaoView

- (IBAction)loginAaction:(id)sender
{
    [WYPublic ifUserHaveLogin];
}
//刷新个人信息
- (void)updateMyInfo
{
    
    UserInfo *user = [[UserInfo alloc]init];
    countLab.text = user.user_name;
    if (user.user_money != nil) {
        moneyLab.text = [NSString stringWithFormat:@"夺币:%@",user.user_money];
    }else{
        moneyLab.text = @"夺币:0";
    }
    if (user.user_jifen != nil) {
        JiFenLab.text = [NSString stringWithFormat:@"积分:%@",user.user_jifen];
    }else{
        JiFenLab.text = @"积分:0";
    }
    [[loginBtn layer] setCornerRadius:3.5];
    [[loginBtn layer] setBorderColor:[UIColor whiteColor].CGColor];
    [[loginBtn layer] setBorderWidth:1.0];
    
    if(![UserInfo isUserLogin]){
        [headerImg setImage:[UIImage imageNamed:@"iphone_5.png"]];
        [loginBtn setHidden:NO];
        [moneyLab setHidden:YES];
        [JiFenLab setHidden:YES];
        [countLab setHidden:YES];
        
    }else
    {
        [headerImg sd_setImageWithURL:[NSURL URLWithString:user.user_header_img_path] placeholderImage:[UIImage imageNamed:@"moren_header"]];
        [loginBtn setHidden:YES];
        [moneyLab setHidden:NO];
        [JiFenLab setHidden:NO];
        [countLab setHidden:NO];
    }

    NSString *show_shopping = [[NSUserDefaults standardUserDefaults] valueForKey:@"show_shopping"];
    if (show_shopping.integerValue == 1 && [UserInfo isUserLogin]) {
        [ChongZhiBtn setHidden:NO];
    }
    else
    {
        [ChongZhiBtn setHidden:YES];
    }
   //请求系统消息
//    [self requestForNews];
    
  
}
 -(void)showBtn
{
    //上架前处理
//    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
//    NSNumber *flag = [user objectForKey:@"user_show_pay"];
//    if ([flag intValue] == 0) {
//        ChongZhiBtn.hidden = YES;
//    }else{
//        ChongZhiBtn.hidden = NO;
//    }
    NSString *show_shopping = [[NSUserDefaults standardUserDefaults] valueForKey:@"show_shopping"];
    [ChongZhiBtn setHidden:YES];
    if (show_shopping.integerValue == 1) {
        [ChongZhiBtn setHidden:NO];
    }

    
}
- (void)awakeFromNib
{
    ChongZhiBtn.hidden = YES;
    _data = [NSMutableArray array];
    CGFloat yy = WYMHEIGHT/568;
    bgnavi.backgroundColor = QBB_RED_COLOR;
    headerImg.layer.masksToBounds = YES;
    headerImg.layer.borderWidth = 2;
    headerImg.frame = CGRectMake(headerImg.frame.origin.x, headerImg.frame.origin.y, headerImg.frame.size.width*yy, headerImg.frame.size.height*yy);
    headerImg.layer.borderColor = [[UIColor whiteColor] CGColor];
    headerImg.layer.cornerRadius = headerImg.frame.size.width/2;
    ChongZhiBtn.layer.masksToBounds = YES;
    ChongZhiBtn.layer.cornerRadius = 2;
    ChongZhiBtn.layer.borderWidth = 1;
    ChongZhiBtn.layer.borderColor = [UIColor whiteColor].CGColor;
    headerImg.layer.masksToBounds = YES;
    headerImg.layer.cornerRadius = headerImg.frame.size.width/2;
    [self updateMyInfo];
    
    //添加圆角通知
    badgeView = [[JSBadgeView alloc] initWithParentView:newImg alignment:JSBadgeViewAlignmentTopRight];
    badgeView.hidden = YES;
    [self updateTongZhi];
    badgeView.badgeBackgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"db_blu_color"]];
    
    CGFloat add = 0;
    [self addSubview:[WYPublic getFenGexian:0 :(CGRectGetMaxY(lab1.frame)+add)*yy :WYMWITH :0.5]];
    [self addSubview:[WYPublic getFenGexian:0 :(CGRectGetMaxY(lab2.frame)+add)*yy :WYMWITH :0.5]];
    [self addSubview:[WYPublic getFenGexian:0 :(CGRectGetMaxY(lab3.frame)+add)*yy :WYMWITH :0.5]];
    [self addSubview:[WYPublic getFenGexian:0 :(CGRectGetMaxY(lab4.frame)+add)*yy :WYMWITH :0.5]];
    [self addSubview:[WYPublic getFenGexian:0 :(CGRectGetMaxY(lab5.frame)+add)*yy :WYMWITH :0.5]];
    
    //头像添加点击手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(imgOnClick)];
    [headerImg addGestureRecognizer:tap];
    headerImg.userInteractionEnabled  = YES;
//    CGFloat fw= WYMWITH/3;
//    UILabel *line1 = [[UILabel alloc]initWithFrame:CGRectMake(fw, (midIng.frame.size.height - 40)*yy, 0.5, 30)];
//    line1.backgroundColor = [UIColor whiteColor];
//    UILabel *line2 = [[UILabel alloc]initWithFrame:CGRectMake(fw*2, (midIng.frame.size.height - 40)*yy, 0.5, 30)];
//    line2.backgroundColor = [UIColor whiteColor];
//    [midIng addSubview:line1];
//    [midIng addSubview:line2];
    
    
}
//请求系统消息
//- (void)requestForNews
//{
//    [_data removeAllObjects];
//    [WYRequest startPostForDicWithUrlStR:[NSString stringWithFormat:@"%@%@",DBB_IP,NEWS_URL] Parameters:nil successBlock:^(NSDictionary *dic) {
//        NSNumber *ret = dic[@"ret"];
//        if ([ret integerValue] == 0) {
//            NSArray *list = dic[@"data"];
//            for (NSDictionary *new in list) {
//                NewsModel *model = [[NewsModel alloc]init];
//                model.news_id = new[@"id"];
//                model.news_title = new[@"title"];
//                model.news_time = new[@"create_time"];
//                //保存数据到数据库
//                if (![[WYDataBase sharedDataBase]isExitInTabNew:model.news_id]) {
//                    [[WYDataBase sharedDataBase]insertNewToTBNew:model];
//                }
//                [_data addObject:model];
//            }
//        }
//        [self updateTongZhi];
//    } failedBlock:^{
//        
//    } needLog:NO];
//}
//刷新圆角通知
- (void)updateTongZhi
{
    NSInteger scanfedCount = 0;
    for (NewsModel *model in _data) {
        NewsModel *restoreModel = [[WYDataBase sharedDataBase]getNewsModelById:model.news_id];
        if (restoreModel.isScanfedFlag == 0) {
            scanfedCount ++;
        }
    }
    badgeView.badgeText = [NSString stringWithFormat:@"%ld",(unsigned long)scanfedCount];
    if (scanfedCount == 0) {
        badgeView.hidden = YES;
    }else{
        badgeView.hidden = NO;
    }
}

//头像点击事件
- (void)imgOnClick
{
    if([WYPublic ifUserHaveLogin]){
        SettingVC *setVC = [[SettingVC alloc]init];
        [[WYMainTabBarVC shareMainTaBarVC].navigationController pushViewController:setVC animated:YES];
    }
}

//充值按钮的监听事件
- (IBAction)addMoneyBtnOnClick:(id)sender {
    [self goToPay];
}
//跳往充值页面
- (void)goToPay
{
    [WYPublic addZheZhaoToWindowWithTitle:nil];
    NSDictionary *params = @{@"uid":[UserInfo getUserID],@"token":[UserInfo getUserToken],@"refresh_token":[UserInfo getRefreshToken]};
    [WYRequest startPostForDicWithUrlStR:[NSString stringWithFormat:@"%@%@",DBB_IP,PEIZHI_URL] Parameters:params successBlock:^(NSDictionary *dic) {
        NSNumber *ret = dic[@"ret"];
        if (ret.intValue == 0) {
//            PayForDbbVC *payDbbVC = [[PayForDbbVC alloc]init];
//            payDbbVC.peizhiDic = dic[@"data"];
//            [[WYMainTabBarVC shareMainTaBarVC].navigationController pushViewController:payDbbVC animated:YES];
            NSInteger is_alipay_mobile = 1;
            NSInteger is_iapppay_wx = 1;
            NSInteger is_iapppay_zf = 1;
            NSInteger is_pingpp_jd = 1;
            NSDictionary *data = dic[@"data"];
            //判断支付宝是否可用
            id available = data[@"valid_pays"][@"alipay_mobile"][@"available"];
            if ( [available class] != [NSNull class]){
                is_alipay_mobile = [(NSNumber*)available integerValue];
            }else{
                is_alipay_mobile = 0;
            }
            
            //判断iapppay微信是否可用
            available =data[@"valid_pays"][@"iapppay"][@"available"];
            if ( [available class] != [NSNull class]){
                is_iapppay_wx = [(NSNumber*)available integerValue];
            }else{
                is_iapppay_wx = 0;
            }
            
            //判断iapppay支付宝是否可用
            available =data[@"valid_pays"][@"iapppay_alipay"][@"available"];
            if ( [available class] != [NSNull class]){
                is_iapppay_zf = [(NSNumber*)available integerValue];
            }else{
                is_iapppay_zf = 0;
            }
            
            //判断pingpp京东支付是否可用
            available =data[@"valid_pays"][@"pingpp"][@"available"];
            if ( [available class] != [NSNull class]){
                is_pingpp_jd = [(NSNumber*)available integerValue];
            }else{
                is_pingpp_jd = 0;
            }
            
            
            ChongZhiController *chongZhiVC = [[ChongZhiController alloc]init];
            chongZhiVC.peizhiDic = dic[@"data"];
            //将是否支付可用的传递给chongZhiVC
            chongZhiVC.is_alipay_mobile = is_alipay_mobile;
            chongZhiVC.is_iapppay_wx  = is_iapppay_wx;
            chongZhiVC.is_iapppay_zfb = is_iapppay_zf;
            chongZhiVC.is_pingpp_jd  = is_pingpp_jd;
            //将支付模型传入chongZhiVC
            [self setInitChongZhiInfoIntoChongZhiController:chongZhiVC dict:dic];
            //获取主tabar的navigationController push充值控制器
            [[WYMainTabBarVC shareMainTaBarVC].navigationController pushViewController:chongZhiVC animated:YES];
            
        }else{
            if(ret.intValue>2000 && ret.intValue < 3000){
                //用户过期，强制重新登录 先删除用户信息
                [UserInfo deleteUserInfo];
                //登录
                [WYPublic ifUserHaveLogin];
                [WYPublic showMessageWithTitle:@"提示：" Msg:@"登录信息已过期"];
            }
            
        }
        [WYPublic removeZheZhaoToWindow];
    } failedBlock:^{
        [WYPublic removeZheZhaoToWindow];
    } needLog:NO];
}

//将获取到的充值模型转导充值控制器中
//此处的dic是原生的dic 需要手动将其他的数据剥离s
- (void)setInitChongZhiInfoIntoChongZhiController:(ChongZhiController*)chongZhiVC dict:(NSDictionary*)dic{
    //支付宝支付模型
    PayInfoModel *zfbPayModel = [[PayInfoModel alloc]init];
    NSDictionary *dict1 = dic[@"data"][@"valid_pays"][@"alipay_mobile"][@"pay_info"];
    if (![dict1 isKindOfClass:[NSNull class]]){
        [zfbPayModel setValuesForKeysWithDictionary:dict1];
    }
    //爱贝微信支付模型
    PayInfoModel *iapppayWXPayModel = [[PayInfoModel alloc]init];
    NSDictionary *dict2 = dic[@"data"][@"valid_pays"][@"iapppay"][@"pay_info"];
    if (![dict2 isKindOfClass:[NSNull class]]){
        [iapppayWXPayModel setValuesForKeysWithDictionary:dict2];
    }
    //爱贝微信支付模型
    PayInfoModel *iapppayzfbPayModel = [[PayInfoModel alloc]init];
    NSDictionary *dict3 = dic[@"data"][@"valid_pays"][@"iapppay_alipay"][@"pay_info"];
    if (![dict3 isKindOfClass:[NSNull class]]){
        [iapppayzfbPayModel setValuesForKeysWithDictionary:dict3];
    }
    //pingpp京东支付模型
    PayInfoModel *pingppJDPayModel = [[PayInfoModel alloc]init];
    NSDictionary *dict4 = dic[@"data"][@"valid_pays"][@"pingpp"][@"pay_info"];
    if (![dict4 isKindOfClass:[NSNull class]]){
        [pingppJDPayModel setValuesForKeysWithDictionary:dict4];
    }
    
    chongZhiVC.zfbModel = zfbPayModel;
    chongZhiVC.iapppayWXModel = iapppayWXPayModel;
    chongZhiVC.iapppayzfbModel = iapppayzfbPayModel;
    chongZhiVC.pingppJDModel = pingppJDPayModel;

}
- (IBAction)morebtnOnClick:(id)sender {
    
    MoreVC *morevc = [[MoreVC alloc]init];
    [[WYMainTabBarVC shareMainTaBarVC].navigationController pushViewController:morevc animated:YES];
}
//一键加群
- (IBAction)addQQqun:(id)sender {
    
    [self joinGroup:[UserInfo getNumForQQ] key:[UserInfo getKeyForQQ]];
}


//一键加群
- (BOOL)joinGroup:(NSString *)groupUin key:(NSString *)key{
    NSString *urlStr = [NSString stringWithFormat:@"mqqapi://card/show_pslcard?src_type=internal&version=1&uin=%@&key=%@&card_type=group&source=external", groupUin,key];
    NSURL *url = [NSURL URLWithString:urlStr];
    if([[UIApplication sharedApplication] canOpenURL:url]){
        [[UIApplication sharedApplication] openURL:url];
        return YES;
    }else{
        UIAlertView *alt = [[UIAlertView alloc]initWithTitle:@"温馨提示：" message:@"未安装qq,或者安装的版本不支持！" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alt show];
    }
    return NO;
}
//透明按钮的监听事件
- (IBAction)tBtnsOnclick:(UIButton *)sender {
    
        switch (sender.tag) {
            case 1:/***************夺宝记录************/
            {
                if( [WYPublic ifUserHaveLogin]){
                    DuoBaoHisVC *hisVC = [[DuoBaoHisVC alloc]init];
                    hisVC.isMyRecordFlag = YES;
                    [[WYMainTabBarVC shareMainTaBarVC].navigationController pushViewController:hisVC animated:YES];
                }
               
            }
                break;
            case 2:/***************中奖记录************/
            {
                if( [WYPublic ifUserHaveLogin]){
                    RewardsVC *reward = [[RewardsVC alloc]init];
                    reward.isMyRecordFlag = YES;
                    [[WYMainTabBarVC shareMainTaBarVC].navigationController pushViewController:reward animated:YES];

                }
             }
                break;
            case 3:/***************晒单记录************/
            {
                if( [WYPublic ifUserHaveLogin]){
                    ShowOrderVC *showvc = [[ShowOrderVC alloc]init];
                    showvc.userId = [UserInfo getUserID];
                    showvc.isMyRecordFlag = YES;
                    [[WYMainTabBarVC shareMainTaBarVC].navigationController pushViewController:showvc animated:YES];
                    
                }
                
            }
                break;
            case 4:/***************收货地址************/
            {
                if( [WYPublic ifUserHaveLogin]){
                    AddressVC *addressVC = [[AddressVC alloc]init];
                    [[WYMainTabBarVC shareMainTaBarVC].navigationController pushViewController:addressVC animated:YES];
     
                }
            }
                break;
            case 5:/***************账户明细************/
            {
                if( [WYPublic ifUserHaveLogin]){
                    MingXiVC *mingxiVC = [[MingXiVC alloc]init];
                    [[WYMainTabBarVC shareMainTaBarVC].navigationController pushViewController:mingxiVC animated:YES];
                    
                }
               
            }
                break;
            case 6:/***************联系客服************/
            {
                NSString *show_customService = [[NSUserDefaults standardUserDefaults] valueForKey:@"show_shopping"];
                if (show_customService.integerValue == 1 ) {
                    
                    //        [customService1 setHidden:NO];
                    //        [customService2 setHidden:NO];
                    //        [customService3 setHidden:NO];
                    //        [customServiceBtn setHidden:NO];
                    WYPublicWeb *web = [[WYPublicWeb alloc]init];
                    web.mtitle = @"用户反馈";
                    NSString *newIp = [DBB_IP stringByReplacingOccurrencesOfString:@"?/" withString:@""];
                    web.urlStr = [NSString stringWithFormat:@"%@%@",newIp,FEEDBACK_URL];
                    [[WYMainTabBarVC shareMainTaBarVC].navigationController pushViewController:web animated:YES];
                    
                    
                    
                }
                else
                {
                    //        [customService1 setHidden:YES];
                    //        [customService2 setHidden:YES];
                    //        [customService3 setHidden:YES];
                    //        [customServiceBtn setHidden:YES];
                    UIAlertView *alertView =[[UIAlertView alloc]initWithTitle:@"官方客服电话" message:@"0755-86200743" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
                    
                    [alertView show];
//                    telprompt
                    
                }
                
                
            }
                break;
            default:
                break;
        }

    
}

//打电话的确认对话框代理
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1){
        [[UIApplication sharedApplication]openURL:[NSURL URLWithString: @"tel://075586200743" ]];
    }
}
//第三方分享
- (IBAction)shareBtnOnclick:(id)sender {
//注意：分享到微信好友、微信朋友圈、微信收藏、QQ空间、QQ好友、来往好友、来往朋友圈、易信好友、易信朋友圈、Facebook、Twitter、Instagram等平台需要参考各自的集成方法
    [UMengRgt shareWithVC:self.father delegate:self];
}
//实现回调方法（可选）：
-(void)didFinishGetUMSocialDataInViewController:(UMSocialResponseEntity *)response
{
    //根据`responseCode`得到发送结果,如果分享成功
    if(response.responseCode == UMSResponseCodeSuccess)
    {
        //得到分享到的微博平台名
        NSLog(@"share to sns name is %@",[[response.data allKeys] objectAtIndex:0]);
    }
}
//系统消息
- (IBAction)newsBtnOnClick:(id)sender {
    //系统消息界面
    NewsVC *newVC = [[NewsVC alloc]init];
    [[WYMainTabBarVC shareMainTaBarVC].navigationController pushViewController:newVC animated:YES];
}

@end
